package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.mapper.LikesMapper;
import com.heima.behavior.service.LikeService;
import com.heima.common.redis.CacheService;
import com.heima.model.behavior.dtos.LikesBehaviorDto;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class LikesServiceImpl extends ServiceImpl<LikesMapper, ApLikesBehavior> implements LikeService {

    @Autowired
    private CacheService cacheService;

    /**
     * 点赞
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult likes(LikesBehaviorDto dto) {
        //cacheService.lRemove(dto.getArticleId() + "likes", 0, 0 + "");
        if (dto.getOperation() == 0) {
            ApLikesBehavior one = getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getArticleId, dto.getArticleId()));
            if (one == null) {
                ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
                apLikesBehavior.setCreateTime(new Date());
                apLikesBehavior.setArticleId(dto.getArticleId());
                apLikesBehavior.setEntryId(AppThreadLocalUtil.getUser().getId());
                apLikesBehavior.setType(0);
                apLikesBehavior.setOperation(0);
                save(apLikesBehavior);
            } else {
                one.setCreateTime(new Date());
                one.setOperation(0);
                updateById(one);
            }
            cacheService.lLeftPush(dto.getArticleId() + "likes", dto.getOperation() + "");
        } else {
            ApLikesBehavior apLikesBehavior = getOne(Wrappers.<ApLikesBehavior>lambdaQuery().eq(ApLikesBehavior::getArticleId, dto.getArticleId()));
            if (apLikesBehavior != null) {
                apLikesBehavior.setOperation(1);
                apLikesBehavior.setCreateTime(new Date());
                updateById(apLikesBehavior);
            }
            cacheService.lRightPop(dto.getArticleId() + "likes");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
